<template>
  <el-form class="addContract">
    <!-- 顶部进度条及按钮 -->
    <el-row class="stepRow">
      <el-col :span="16">
        <el-steps
          style="height: 30px"
          :active="active"
          finish-status="success"
          simple
        >
          <el-step title="合同基本信息" />
          <el-step title="付款方式设置" />
          <el-step title="合同材料信息" />
        </el-steps>
      </el-col>
      <el-col :span="8" style="text-align: right">
        <el-button v-show="active > 0" color="#1E3485" @click="prevStep"
          >上一步</el-button
        >
        <el-button color="#1E3485" @click="nextStep">{{
          active < 2 ? "保存，下一步" : "保存"
        }}</el-button>
        <el-button
          v-show="active == 2"
          v-if="!queryParams.examine"
          color="#1E3485"
          @click="saveOrSubmit"
          >保存并提交</el-button
        >
        <closeTagButton id="closeTagButtonRef" />
      </el-col>
    </el-row>
    <!-- stepOne -->
    <div v-if="active === 0" class="stepOne">
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-form
          ref="contractModelRef1"
          label-width="150px"
          :rules="rulesForStepOne"
          :model="contractModel"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="主合同名称" required prop="mainContractName">
                <el-input
                  v-model="contractModel.mainContractName"
                  placeholder="请选择 主销售合同"
                  @click="showContractSelectDialog"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同编号" required prop="contractNo">
                <el-input
                  v-model="contractModel.contractNo"
                  placeholder="请输入 合同编号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同名称" required prop="contractName">
                <el-input
                  v-model="contractModel.contractName"
                  placeholder="请输入 合同名称"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div class="card-header">
            <span>合约双方信息</span>
          </div>
        </template>
        <el-form label-width="150px" :model="contractModel">
          <el-row>
            <el-col :span="24">
              <el-form-item label="合同类型" required>
                <el-radio-group v-model="contractModel.contractMethod" disabled>
                  <el-radio value="0" size="default"
                    >电线电缆以及光纤光缆</el-radio
                  >
                  <el-radio value="1" size="default">电梯及扶梯</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="供应厂商">
                <el-select
                  v-model="contractModel.supplierCategoryName"
                  placeholder=""
                  disabled
                >
                  <el-option
                    v-for="item in supplierCategoryNameOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="20" required prop="supplierDeptName">
                <el-input v-model="contractModel.supplierDeptName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="询价单号">
                <el-input v-model="contractModel.inquiryNo" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商">
                <el-select
                  v-model="contractModel.supplyDeptName"
                  placeholder=""
                  disabled
                >
                  <el-option
                    v-for="item in supplyDeptOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购单位">
                <el-input v-model="contractModel.purchaseDeptName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="采购负责人">
                <el-input v-model="contractModel.purchasePersonName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话">
                <el-input v-model="contractModel.purchasePhone" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称">
                <el-input v-model="contractModel.projectName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目所属分公司">
                <el-input v-model="contractModel.projectDeptName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目联系人">
                <el-input v-model="contractModel.projectManager" disabled>
                  <template #append>
                    <el-icon style="cursor: pointer"><Search /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话">
                <el-input
                  v-model="contractModel.projectManagerPhone"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目地址">
                <el-input v-model="contractModel.projectAddress" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="允许超合同金额" required>
                <el-radio-group v-model="contractModel.isPriceFlag" disabled>
                  <el-radio value="0" size="default">不允许</el-radio>
                  <el-radio value="1" size="default">允许</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="允许超合同材料数量" required>
                <el-radio-group v-model="contractModel.isNumFlag" disabled>
                  <el-radio value="0" size="default">不允许</el-radio>
                  <el-radio value="1" size="default">允许</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div class="card-header">
            <span>其他信息</span>
          </div>
        </template>
        <el-form
          ref="contractModelRef2"
          label-width="180px"
          :rules="rulesForStepOne"
          :model="contractModel"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="合同总量">
                <el-input v-model="contractModel.contractNum" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签订日期" required prop="signDate">
                <el-date-picker
                  v-model="contractModel.signDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择 签订日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="回款截止日期">
                <el-date-picker
                  v-model="contractModel.paymentDeadlineDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择 回款截止日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="合同总额含税（元）">
                <el-input v-model="contractModel.contractTotalPrice" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同总额实际含税（元）">
                <el-input
                  v-model="contractModel.contractTotalRealPrice"
                  placeholder="请输入 合同总额实际含税金额"
                  :disabled="queryParams.examine === 'already'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="20" style="width: 80%">
                <el-input
                  v-model="contractModel.contractTotalRealPriceMark"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input
                  v-model="contractModel.mark"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入 备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同附件" required prop="contractFile">
                <el-upload
                  v-model:file-list="fileList"
                  :action="uploadUrl"
                  :headers="headers"
                  :on-preview="handlePreview"
                  :on-success="handleSuccess"
                  :before-remove="beforeRemove"
                  multiple
                  style="width: 80%"
                >
                  <el-button :icon="Upload" color="#1E3485">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">文件大小不能超过10M</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <!-- stepTwo -->
    <div v-if="active === 1" class="stepTwo">
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div class="card-header">
            <span>其他信息</span>
          </div>
        </template>
        <el-form
          ref="secondContractModelRef"
          label-width="180px"
          :rules="rulesForStepTwo"
          :model="secondContractModel"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="价格类型" required prop="priceType">
                <el-radio-group v-model="secondContractModel.priceType">
                  <el-radio value="0" size="default">锁定</el-radio>
                  <el-radio
                    v-if="contractModel.contractMethod != '1'"
                    value="1"
                    size="default"
                    >浮动</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                v-if="secondContractModel.priceType != '1'"
                label="支付说明"
              >
                <el-input
                  v-model="secondContractModel.priceTypeMark"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入 备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                v-if="secondContractModel.priceType === '1'"
                label="支付说明"
                required
                prop="priceTypeMark"
              >
                <el-input
                  v-model="secondContractModel.priceTypeMark"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入 备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item
                v-if="secondContractModel.priceType === '1'"
                label="基准价（元）"
                required
                prop="basePrice"
              >
                <el-input v-model="secondContractModel.basePrice" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                v-if="secondContractModel.priceType === '1'"
                label="涨幅"
                required
                prop="increasePrice"
              >
                <el-input v-model="secondContractModel.increasePrice" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                v-if="secondContractModel.priceType === '1'"
                label="涨幅比率"
                required
                prop="increaseRate"
              >
                <el-input v-model="secondContractModel.increaseRate" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="付款周期" required prop="paymentCycle">
                <el-radio-group
                  v-model="secondContractModel.paymentCycle"
                  @change="changePaymentCycle"
                >
                  <el-radio value="0" size="default">到货结算</el-radio>
                  <el-radio value="1" size="default">款清发货</el-radio>
                  <el-radio value="2" size="default">月度结算</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="付款节点">
                <el-button color="#1E3485" @click="addPaymentNode"
                  >添加付款节点</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <vxe-table
          border
          min-height="300px"
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="nodePayTableData"
          :loading="nodePayTableLoading"
          size="mini"
          style="margin-left: 180px"
        >
          <vxe-column
            v-for="column in nodePayTableColumns"
            :key="column.field"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :min-width="column.width"
            :align="column.align"
          >
            <!-- 节点类型 -->
            <template
              v-if="column.field == 'nodeType'"
              v-slot:default="{ row }"
            >
              <vxe-select
                v-model="row.nodeType"
                placehoder=""
                style="display: inline-block"
                placement="bottom-start"
                clearable
                @change="handleNodeTypeChange(row)"
              >
                <vxe-option
                  v-for="item in nodeTypeOptions"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                  :disabled="item.disabled"
                />
              </vxe-select>
            </template>
            <!-- 付款节点时间 && 电线电缆 -->
            <template
              v-else-if="
                column.field === 'payTime' &&
                contractModel.contractMethod === '0'
              "
              v-slot:default="{ row }"
            >
              <span v-if="row.nodeType == '0'">合同签订后</span>
              <span v-if="row.nodeType == '1'">订单签订后</span>
              <vxe-select
                v-if="row.nodeType == '2'"
                v-model="row.nodeTriggerType"
                style="width: 30%; display: inline-block"
                placement="bottom-start"
                @change="handleNodeTriggerTypeChange(row)"
              >
                <vxe-option
                  v-for="(item, index) in getAvailableNodeTriggerTypeList(
                    secondContractModel.paymentCycle,
                    row.nodeType
                  )"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                />
              </vxe-select>
              &nbsp;
              <!-- 付款节点时间 - 自定义&&月度结算&&订单实付款 -->
              <vxe-input
                v-if="
                  row.nodeTriggerType === '9' &&
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeType === '2'
                "
                v-model="row.nodeTriggerTypeName"
                style="width: 30%; display: inline-block"
              />
              <!-- 付款节点时间 - 自定义&&月度结算&&非订单实付款 (用不上) -->
              <!-- 付款节点时间 - 自定义&&非月度结算&&订单实付款 -->
              <vxe-input
                v-if="
                  row.nodeTriggerType === '9' &&
                  secondContractModel.paymentCycle != '2' &&
                  row.nodeType === '2'
                "
                v-model="row.nodeTriggerTypeName"
                style="width: 30%; display: inline-block"
              />
              <!-- 付款节点时间 - 自定义&&非月度结算&&非订单实付款 (用不上) -->
              <!-- 付款节点时间 - 非自定义&&月度结算&&订单实付款 -->
              <vxe-input
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeType === '2'
                "
                v-model="row.monthDay"
                type="number"
                style="width: 15%; display: inline-block"
                :min="0"
              />
              <span
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeType === '2'
                "
                >（个月）</span
              >
              <vxe-input
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeType === '2'
                "
                v-model="row.natureDay"
                type="number"
                style="width: 15%; display: inline-block"
                :min="0"
              />
              <span
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeType === '2'
                "
                >（日）</span
              >
              <!-- 付款节点时间 - 非自定义&月度结算&&非订单实付款 -->
              <vxe-input
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeType != '2'
                "
                v-model="row.natureDay"
                type="number"
                style="width: 15%; display: inline-block"
                :min="0"
              />
              <span
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeType != '2'
                "
                >（个自然日）</span
              >
              <!-- 付款节点时间 - 非自定义&&非月度结算&&订单实付款 -->
              <vxe-input
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle != '2' &&
                  row.nodeType === '2'
                "
                v-model="row.natureDay"
                type="number"
                style="width: 15%; display: inline-block"
                :min="0"
              />
              <span
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle != '2' &&
                  row.nodeType === '2'
                "
                >（个自然日）</span
              >
              <!-- 付款节点时间 - 非自定义&&非月度结算&&非订单实付款 -->
              <vxe-input
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle != '2' &&
                  row.nodeType != '2'
                "
                v-model="row.natureDay"
                type="number"
                style="width: 15%; display: inline-block"
                :min="0"
              />
              <span
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle != '2' &&
                  row.nodeType != '2'
                "
                >（个自然日）</span
              >
              <!-- 一直显示 -->
              <span>，完成回款</span>
            </template>
            <!-- 付款节点时间 && 电梯扶梯 -->
            <template
              v-else-if="
                column.field === 'payTime' &&
                contractModel.contractMethod === '1'
              "
              v-slot:default="{ row }"
            >
              <span v-if="row.nodeType == '0'">合同签订后</span>
              <span v-if="row.nodeType == '1'">订单签订后</span>
              <vxe-select
                v-if="row.nodeType == '2'"
                v-model="row.nodeTriggerType"
                style="width: 35%; display: inline-block"
                placement="bottom-start"
                @change="handleNodeTriggerTypeChange(row)"
              >
                <vxe-option
                  v-for="item in nodeTriggerTypeForLift"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </vxe-select>
              &nbsp;
              <!-- 自定义 -->
              <vxe-input
                v-if="row.nodeTriggerType === '9'"
                v-model="row.nodeTriggerTypeName"
                style="width: 50%; display: inline-block"
              />
              <!-- 非自定义 非月度结算-->
              <vxe-input
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle != '2'
                "
                v-model="row.natureDay"
                type="number"
                style="width: 15%; display: inline-block"
                :min="0"
              />
              <span
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle != '2'
                "
                >（个自然日）</span
              >
              <!-- 非自定义 月度结算-->
              <vxe-input
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2'
                "
                v-model="row.monthDay"
                type="number"
                style="width: 15%; display: inline-block"
                :min="0"
              />
              <span
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2'
                "
                >（个月）</span
              >
              <vxe-input
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2'
                "
                v-model="row.natureDay"
                type="number"
                style="width: 15%; display: inline-block"
                :min="0"
              />
              <span
                v-if="
                  row.nodeTriggerType != '9' &&
                  secondContractModel.paymentCycle === '2'
                "
                >（日）</span
              >
            </template>
            <!-- 完成付款比例 -->
            <template
              v-else-if="column.field == 'backPayRate'"
              v-slot:default="{ row }"
            >
              <vxe-input v-model="row.backPayRate" type="number" :min="0" />
            </template>
            <!-- 节点说明 -->
            <template
              v-else-if="column.field == 'nodeMark'"
              v-slot:default="{ row }"
            >
              <!-- 自定义 && 月度结算 && 订单实付款 -->
              <span
                v-if="
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeTriggerType === '9' &&
                  row.nodeType === '2'
                "
              >
                {{ row.nodeTriggerTypeName }}，完成订单总金额
                {{ row.backPayRate }} %的回款
              </span>
              <!-- 自定义 && 月度结算 && 非订单实付款 （用不上）-->
              <!-- 自定义 && 非月度结算 && 订单实付款 -->
              <span
                v-if="
                  secondContractModel.paymentCycle != '2' &&
                  row.nodeTriggerType === '9' &&
                  row.nodeType === '2'
                "
              >
                {{ row.nodeTriggerTypeName }}，完成订单总金额
                {{ row.backPayRate }} %的回款
              </span>
              <!-- 自定义 && 非月度结算 && 非订单实付款（用不上） -->
              <!-- 非自定义 && 月度结算 && 订单实付款 -->
              <span
                v-if="
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeTriggerType != '9' &&
                  row.nodeType === '2'
                "
              >
                {{ row.nodeTriggerTypeName }}
                {{ row.monthDay }} 个月 {{ row.natureDay }} 日，完成订单总金额
                {{ row.backPayRate }} %的回款
              </span>
              <!-- 非自定义 && 月度结算 && 非订单实付款）-->
              <span
                v-if="
                  secondContractModel.paymentCycle === '2' &&
                  row.nodeTriggerType != '9' &&
                  row.nodeType != '2'
                "
              >
                {{ row.nodeTriggerTypeName }}
                {{ row.natureDay }} 个自然日，完成订单总金额
                {{ row.backPayRate }} %的回款
              </span>
              <!-- 非自定义 && 非月度结算 && 订单实付款 -->
              <span
                v-if="
                  secondContractModel.paymentCycle != '2' &&
                  row.nodeTriggerType != '9' &&
                  row.nodeType === '2'
                "
              >
                {{ row.nodeTriggerTypeName }}
                {{ row.natureDay }} 个自然日，完成订单总金额
                {{ row.backPayRate }} %的回款
              </span>
              <!-- 非自定义 && 非月度结算 && 非订单实付款-->
              <span
                v-if="
                  secondContractModel.paymentCycle != '2' &&
                  row.nodeTriggerType != '9' &&
                  row.nodeType != '2'
                "
              >
                {{ row.nodeTriggerTypeName }}
                {{ row.natureDay }} 个自然日，完成订单总金额
                {{ row.backPayRate }} %的回款
              </span>
            </template>
            <!-- 操作 -->
            <template
              v-else-if="column.field == 'operate'"
              v-slot:default="{ row }"
            >
              <vxe-button
                type="text"
                size="small"
                @click="deletePayNodeData(row)"
              >
                删除
              </vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
    </div>
    <!-- stepThree -->
    <div v-if="active === 2" class="stepThree">
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div class="step3Head">
            <span>合同材料</span>
            <div class="step3HeadBtn">
              <el-button color="#1E3485" @click="showMaterialSelectDialog()"
                >添加</el-button
              >
              <el-button color="#1E3485" @click="downloadTemplate()"
                >下载模板</el-button
              >
              <el-button color="#1E3485" @click="triggerFileSelect()"
                >导入</el-button
              >
              <el-button color="#1E3485" @click="exportMaterialList()"
                >导出</el-button
              >
              <input
                ref="fileInputRef"
                type="file"
                style="display: none"
                @change="handleFileChange"
              />
            </div>
            <div class="step3HeadText" style="display: none">
              <div class="step3HeadTips" style="width: 170px">
                <div
                  class="tipsTitle"
                  style="background-color: rgb(67, 94, 194); color: white"
                >
                  <span>蓝色底色</span>
                </div>
                <div class="tipsContent">
                  <span>复制的材料</span>
                </div>
              </div>
              <div class="step3HeadTips" style="width: 200px">
                <div
                  class="tipsTitle"
                  style="background-color: rgb(204, 204, 204); color: black"
                >
                  <span>灰色底色</span>
                </div>
                <div class="tipsContent">
                  <span>材料字典中不存在</span>
                </div>
              </div>
              <div class="step3HeadTips" style="width: 200px">
                <div class="tipsTitle" style="color: red">
                  <span>文字红色</span>
                </div>
                <div class="tipsContent">
                  <span>和材料字典不同</span>
                </div>
              </div>
            </div>
            <div class="step3EndBtn">
              <el-button color="#1E3485" @click="complexDeleteMaterials()"
                >批量删除</el-button
              >
              <el-button color="#1E3485" style="display: none">完成</el-button>
            </div>
          </div>
        </template>
        <vxe-table
          ref="materialTableRef"
          border
          show-footer
          header-align="center"
          min-height="450"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="materialTableData"
          :loading="materialTableLoding"
          :footer-data="materialTableFooterData"
          size="mini"
        >
          <vxe-column type="checkbox" width="60" fixed="left" align="center" />
          <vxe-column
            type="seq"
            field="seq"
            title="序号"
            min-width="50"
            align="center"
            fixed="left"
          />
          <vxe-column title="" width="60" align="center">
            <template v-slot="{ row }">
              <vxe-button type="text" @click="copyRow(row)">
                <el-icon><Plus /></el-icon>
              </vxe-button>
            </template>
          </vxe-column>
          <vxe-column
            v-for="column in materialTableColumns"
            :key="column.field"
            header-align="center"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :min-width="column.width"
            :align="column.align"
          >
            <template
              v-if="column.field == 'materialUnit'"
              v-slot:default="{ row }"
            >
              <vxe-input v-model="row.materialUnit" align="center" />
            </template>
            <template
              v-else-if="column.field == 'materialBrand'"
              v-slot:default="{ row }"
            >
              <vxe-input v-model="row.materialBrand" align="center" />
            </template>
            <template
              v-else-if="column.field == 'materialNum'"
              v-slot:default="{ row }"
            >
              <vxe-input
                v-model="row.materialNum"
                align="right"
                @change="changeCalculated(row, 'materialNum')"
              />
            </template>
            <template
              v-else-if="column.field == 'includingTaxUnitPrice'"
              v-slot:default="{ row }"
            >
              <vxe-input
                v-model="row.includingTaxUnitPrice"
                align="right"
                @change="changeCalculated(row, 'includingTaxUnitPrice')"
              />
            </template>
            <template
              v-else-if="column.field == 'excludingTaxUnitPrice'"
              v-slot:default="{ row }"
            >
              <vxe-input
                v-model="row.excludingTaxUnitPrice"
                align="right"
                @change="changeCalculated(row, 'excludingTaxUnitPrice')"
              />
            </template>
            <template
              v-else-if="column.field == 'tax'"
              v-slot:default="{ row }"
            >
              <vxe-input
                v-model="row.tax"
                align="center"
                @change="changeCalculated(row, 'tax')"
              />
            </template>
            <template
              v-else-if="column.field == 'includingTaxTotalPrice'"
              v-slot:default="{ row }"
            >
              <vxe-input
                v-model="row.includingTaxTotalPrice"
                align="right"
                @change="changeCalculated(row, 'includingTaxTotalPrice')"
              />
            </template>
            <template
              v-else-if="column.field == 'materialMark'"
              v-slot:default="{ row }"
            >
              <vxe-input v-model="row.materialMark" />
            </template>
            <!-- 复制的行背景色为灰色 -->
            <!-- <template
              v-else-if="column.field == 'isCopy'"
              v-slot:default="{ row }"
            >
              <span v-if="row.isCopy == '0'">否</span>
              <span v-if="row.isCopy == '1'">是</span>
            </template> -->
          </vxe-column>
          <vxe-column title="操作" fixed="right" width="100" align="center">
            <!-- 操作列按钮 -->
            <template v-slot="{ row }">
              <vxe-button
                type="text"
                size="small"
                @click="singleDeleteMeterial(row)"
                >删除</vxe-button
              >
            </template>
          </vxe-column>
        </vxe-table>
        <!-- 由于表格分页存在数据实例销毁特性，取消分页 -->
        <!-- <vxe-pager
          v-model:current-page="materialTablePage.currentPage"
          v-model:page-size="materialTablePage.pageSize"
          :layouts="[
            'Sizes',
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'FullJump',
            'Total'
          ]"
          :total="materialTablePage.total"
          size="small"
          @page-change="materialTablePageChange"
        /> -->
      </el-card>
    </div>
    <!-- 弹窗组件 -->
    <div class="dialogs">
      <!-- 选择主合同弹窗 -->
      <contractSelectDialog
        :visible="mainContractSelectVisible"
        @close="closeContractSelectDialog"
        @confirm="contractSelectConfirm"
      />
      <!-- 文件预览弹窗 -->
      <filePreview
        :visible="filePreviewDialogVisible"
        :fileUrl="fileUrl"
        @close="closeFilePreview"
      />
      <!-- 选择材料弹窗 -->
      <materialSelectDialog
        :visible="materialSelectDialogVisible"
        @close="closeMaterialSelectDialog"
        @confirm="materialSelectConfirm"
      />
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { Search, Upload, Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { VxeTablePropTypes } from "vxe-table";
import { useRoute } from "vue-router";
import closeTagButton from "@/components/closeTagButton.vue";
import filePreview from "@/components/filePreview.vue";
import contractSelectDialog from "./dialog/contractSelectDialog.vue";
import projectSelectDialog from "./dialog/projectSelectDialog.vue";
import contactsSelectDialog from "./dialog/contactsSelectDialog.vue";
import consigneeSelectDialog from "./dialog/consigneeSelectDialog.vue";
import supplierSelectDialog from "./dialog/supplierSelectDialog.vue";
import materialSelectDialog from "./dialog/materialSelectDialog.vue";
import type { Ref } from "vue";
import type {
  UploadUserFile,
  UploadProps,
  UploadFile,
  UploadFiles
} from "element-plus";
import type { mainContractType } from "@/views/ERP_sales/type/sales_type";
import { cloneDeep } from "@pureadmin/utils";
import { headers, uploadUrl, getDictDetail } from "@/api/utils";
import {
  getContractNo,
  saveSalesContractStepOne,
  saveProjectReceiver,
  getSalesContractDetail,
  getProjectReceiver,
  getNodePayFormData,
  getNodePayTableData,
  saveNodePayData,
  importMaterialList,
  getContractMaterialList,
  getContractMaterialFooter,
  deleteContractMaterial,
  saveContractMeterialData,
  deleteReceiverContacts,
  deletePayNode,
  submitAudit
} from "@/api/ERP_sales";
import { exportMaterialListFile } from "@/api/ERP_public";

////////////////////// 公共 //////////////////////
// 接收路由传参
const route = useRoute();
const queryParams = route.query;
// 进度条
let active: Ref<number> = ref(0);
// 合同ID - 新增时保存第一页数据后获取
let publicContractID = ref();
// 上一步按钮事件
const prevStep = () => {
  active.value -= 1;
};
////////////////////// 第一步 //////////////////////
// stepOne-主合同表单数据
let contractModel = reactive({
  // 合同ID
  id: undefined,
  // 合同类型
  contractType: "1", // 合同类型：0-主合同，1-补充合同
  // 主合同信息
  mainContractId: "", // 主合同ID
  mainContractNo: "", // 主合同编号
  mainContractName: "", // 主合同名称
  tenantId: "", // 租户ID
  // bindContractStatus: "", //绑定合同的状态 0-未绑定,1-已绑定
  // 项目信息
  contractMethod: "0", // 合同方式 0-电线电缆，1-电梯
  purchaseDeptId: "", // 采购单位ID - 自动带出不展示
  purchaseDeptName: "", // 采购单位
  projectDeptId: "", // 所属单位ID
  projectDeptName: "", // 项目所属分公司
  projectId: "", // 项目ID - 自动带出不展示
  projectName: "", // 项目名称
  projectAddress: "", // 项目地址
  projectManagerId: "", // 项目联系人ID - 自动带出不展示
  projectManager: "", // 项目联系人
  projectManagerPhone: "", // 项目联系人电话
  // 合约方信息
  supplierCategoryId: "", //供应商品类ID - 自动带出不展示
  supplierCategoryName: "", // 供应商品类
  supplierDeptId: "", // 供应商厂商ID - 自动带出不展示
  supplierDeptName: "", // 供应商厂商
  supplyDeptId: "", // 供应商ID - 自动带出不展示
  supplyDeptName: "", // 供应商
  inquiryNo: "", // 询价单号
  contractNo: "", // 合同编号
  contractName: "", // 合同名称
  purchasePersonId: "", // 采购负责人ID - 自动带出不展示
  purchasePersonName: "", // 采购负责人
  purchasePhone: "", // 联系电话
  isPriceFlag: undefined, // 允许超合同金额 0-否，1-是
  isNumFlag: undefined, // 允许超合同材料数量 0-否，1-是
  // 其他信息
  contractNum: undefined, // 合同总量
  signDate: "", // 签订日期
  paymentDeadlineDate: "", // 回款截止日期
  contractTotalPrice: undefined, // 合同总额含税（元）
  contractTotalRealPrice: undefined, // 合同总额实际含税（元）
  contractTotalRealPriceMark: "", // 合同总额实际含税备注
  mark: "", // 备注
  contractFile: "" // 合同文件(数组转成字符串格式)
});
let contractModelRef1 = ref();
let contractModelRef2 = ref();
// 供应商品类列表
const supplierCategoryNameOptions = ref([]);
async function getSupplierCategoryNameOptions() {
  const res: any = await getDictDetail({
    key: "supplier_type"
  });
  supplierCategoryNameOptions.value.splice(
    0,
    supplierCategoryNameOptions.value.length
  );
  res.data.forEach((item: any) => {
    supplierCategoryNameOptions.value.push({
      key: item.id,
      label: item.value,
      value: item.key
    });
  });
}
// 供应商列表
const supplyDeptOptions = ref([]);
async function getSupplyDeptOptions() {
  const res: any = await getDictDetail({
    key: "supply_dept"
  });
  supplyDeptOptions.value.splice(0, supplyDeptOptions.value.length);
  res.data.forEach((item: any) => {
    supplyDeptOptions.value.push({
      key: item.key,
      label: item.value,
      value: item.value
    });
  });
}
// 联系人表
let contactsTableData = ref([]);
// 联系人对照表
let contractTableOrigData = ref([]);
// 上传按钮&相关事件
let fileList = ref<UploadUserFile[]>([]);
let filePreviewDialogVisible = ref(false);
let fileUrl = ref("");
const handlePreview: UploadProps["onPreview"] = (uploadFile: UploadFile) => {
  if (uploadFile.response) {
    const response = uploadFile.response as unknown as any;
    window.open(response.data.url, "_blank");
  } else {
    window.open(uploadFile.url, "_blank");
  }
};
function closeFilePreview(val: boolean) {
  filePreviewDialogVisible.value = val;
}
// 文件上传成功,传参赋值，格式修改
const handleSuccess = uploadFile => {
  let fileItems = [];
  if (contractModel.contractFile != "") {
    fileItems = JSON.parse(contractModel.contractFile);
  }
  let tempValue: any = {};
  tempValue.fileUrl = uploadFile.data.url;
  tempValue.fileSuffix =
    "." +
    uploadFile.data.name.substring(uploadFile.data.name.lastIndexOf(".") + 1);
  tempValue.fileOriginName = uploadFile.data.name;
  fileItems.push(tempValue);
  contractModel.contractFile = JSON.stringify(fileItems);
};
const beforeRemove = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  let fileItems = JSON.parse(contractModel.contractFile);
  fileItems.forEach((item, index) => {
    if (item.fileOriginName == uploadFile.name) {
      fileItems.splice(index, 1);
    }
  });
  contractModel.contractFile = JSON.stringify(fileItems);
  return true;
};
// 表单校验-stepOne
const rulesForStepOne = reactive({
  mainContractName: [
    { required: true, message: "请选择主销售合同", trigger: "blur" }
  ],
  contractNo: [{ required: true, message: "请输入合同编号", trigger: "blur" }],
  contractName: [
    { required: true, message: "请输入合同名称", trigger: "blur" }
  ],
  signDate: [{ required: true, message: "请选择签订日期", trigger: "blur" }],
  contractFile: [{ required: true, message: "请上传合同附件", trigger: "blur" }]
});
// 选择主合同弹窗
let mainContractSelectVisible = ref(false);
function showContractSelectDialog() {
  mainContractSelectVisible.value = true;
}
function closeContractSelectDialog(val: boolean) {
  mainContractSelectVisible.value = val;
}
const contractSelectConfirm = async data => {
  await getMainContractDetail(data.mianContractId);
};
// 获取主销售合同详情&赋值
async function getMainContractDetail(id) {
  let params: ApiParams = {};
  params.id = id;
  try {
    const response: ApiResponse = await getSalesContractDetail(params);
    // 参数赋值
    contractModel.mainContractId = response.data.id;
    contractModel.mainContractNo = response.data.contractNo;
    contractModel.mainContractName = response.data.contractName;
    contractModel.contractMethod = response.data.contractMethod;
    contractModel.purchaseDeptId = response.data.purchaseDeptId;
    contractModel.purchaseDeptName = response.data.purchaseDeptName;
    contractModel.projectDeptId = response.data.projectDeptId;
    contractModel.projectDeptName = response.data.projectDeptName;
    contractModel.projectId = response.data.projectId;
    contractModel.projectName = response.data.projectName;
    contractModel.projectAddress = response.data.projectAddress;
    contractModel.projectManagerId = response.data.projectManagerId;
    contractModel.projectManager = response.data.projectManager;
    contractModel.projectManagerPhone = response.data.projectManagerPhone;
    contractModel.supplierCategoryId = response.data.supplierCategoryId;
    contractModel.supplierCategoryName = response.data.supplierCategoryName;
    contractModel.supplierDeptId = response.data.supplierDeptId;
    contractModel.supplierDeptName = response.data.supplierDeptName;
    contractModel.supplyDeptId = response.data.supplyDeptId;
    contractModel.supplyDeptName = response.data.supplyDeptName;
    contractModel.inquiryNo = response.data.inquiryNo;
    contractModel.purchasePersonId = response.data.purchasePersonId;
    contractModel.purchasePersonName = response.data.purchasePersonName;
    contractModel.purchasePhone = response.data.purchasePhone;
    contractModel.isPriceFlag = response.data.isPriceFlag.toString();
    contractModel.isNumFlag = response.data.isNumFlag.toString();
    contractModel.contractNo = response.data.contractNo + "-02";
  } catch (error) {
    ElMessage.error("获取主销售合同详情失败，重新选择");
  }
}
// 保存第一步的数据请求
async function saveContractStepOne() {
  let params: ApiParams = {};
  for (let key in contractModel) {
    let value = contractModel[key];
    if (value !== "" && value !== undefined) {
      params[key] = value;
    }
  }
  const response: ApiResponse = await saveSalesContractStepOne(params);
  if (response.code === 200) {
    // 获取合同ID
    contractModel.id = response.data;
    publicContractID.value = response.data;
    // 根据合同ID，将项目收货人中的数据提交
    let receiverInfo: any = {};
    for (let item in contactsTableData.value) {
      receiverInfo.id = contactsTableData.value[item].id;
      receiverInfo.name = contactsTableData.value[item].realName;
      receiverInfo.phone = contactsTableData.value[item].phone;
      receiverInfo.contractId = contractModel.id;
      await saveProjectReceiver(receiverInfo);
    }
  }
}
// 获取销售合同详情 - 第一页
async function getStepOneData() {
  if (queryParams.action != "add" && queryParams.id) {
    let params: ApiParams = {};
    params.id = queryParams.id;
    publicContractID.value = queryParams.id;
    // 获取第一页数据
    const response: ApiResponse = await getSalesContractDetail(params);
    if (response.code === 200 && response.data) {
      for (let key in contractModel) {
        let value = response.data[key];
        contractModel[key] = value;
      }
      contractModel.isNumFlag = response.data.isNumFlag.toString();
      contractModel.isPriceFlag = response.data.isPriceFlag.toString();
      if (response.data.contractFile) {
        contractModel.contractFile = response.data.contractFile;
        JSON.parse(response.data.contractFile).forEach(file => {
          fileList.value.push({
            name: file.fileOriginName,
            url: file.fileUrl
          });
        });
      }
    }
  }
}
// 获取当前项目收货人列表
async function getProjectReceiverList() {
  let params: ApiParams = {};
  params.contractId = contractModel.id;
  const response: ApiResponse = await getProjectReceiver(params);
  if (response.code === 200) {
    contactsTableData.value = response.data.map(item => ({
      id: item.id,
      realName: item.name,
      phone: item.phone,
      tenantId: item.tenantId
    }));
  }
}
////////////////////// 第二步 //////////////////////
// stepTwo-付款节点表单数据
const secondContractModelRef = ref();
let secondContractModel = reactive({
  // 带出数据
  id: "", // 第二步的主键ID - 新增时不存在不传，编辑时存在
  contractId: "", // 合同ID
  // 表单数据
  priceType: "0", // 价格类型 0-锁定，1-浮动
  priceTypeMark: "", // 支付说明
  basePrice: 0.0, // 基础价格（元）
  increasePrice: 0.0, // 涨幅
  increaseRate: 0.0, // 涨幅比例
  paymentCycle: "0", // 付款周期 0-到货结算, 1-款清发货, 2-月度结算
  paymentReconciliationMonth: 0, // 月度结算时-收货确认对账几月
  paymentReconciliationDay: 0, // 月度结算时-收货确认对账几日(完成对账)
  contractPreStatus: "0", // 合同预付款 0-未开启，1-已开启
  ordePreStatus: "0", // 订单预付款 0-未开启，1-已开启
  nodePaySaveDtoList: [] // 付款节点表数据
});
// 默认数据 - 点击增加节点按钮新增
const defaultPayNodeData = reactive({
  id: "", // 主键
  contractId: "", // 合同ID - 保存时赋值
  nodeType: "2", // 节点类型 0-合同预付款 1-订单预付款 2-订单实付款
  nodeTypeName: "订单实付款", // 节点名称
  nodeTriggerType: "", // 触发节点类型
  nodeTriggerTypeName: "", // 触发节点类型名称
  autoStatus: "1", // 【自定义的都是手动】自动/手动，自动输入天数，手工输入日期 0=手动(自定义时默认为0)，1=自动
  monthDay: 0, // 月份数
  natureDay: 0, // 自然日天数
  backPayRate: 0, // 回款比率%
  nodeMark: "" // 节点说明
  // status: "" // 【前端暂时不做展示和修改】状态 0-待回款/付款 1-回款/付款中  2-完成回款/付款
});
// 节点类型列 - 选择框
const nodeTypeOptions = reactive([
  { value: "0", label: "合同预付款", disabled: false },
  { value: "1", label: "订单预付款", disabled: false },
  { value: "2", label: "订单实付款", disabled: false }
]);
// 付款节点时间列 - 选择框
const nodeTriggerTypeOptions = reactive([
  { value: "0", label: "合同签订后" }, // 勾选合同预付款 的数据 (未勾选则：全部不可选)
  { value: "1", label: "供应商确认订单后" }, // 勾选订单预付款 的数据 (未勾选则：到货结算、款清发货 可选)
  { value: "2", label: "供应商确认供货后" }, // 到货结算 可选
  { value: "3", label: "项目部确认验收后" }, // 到货结算 月度结算 可选
  { value: "4", label: "对账完成后" }, // 款清发货 可选
  { value: "5", label: "对账确认后" }, // 到货结算 款清发货 可选
  { value: "6", label: "结算确认后" }, // 到货结算 款清发货 可选
  { value: "9", label: "自定义" } // 均 可选
]);
const nodeTriggerTypeForLift = reactive([
  { value: "0", label: "预付款，订单签订后" },
  { value: "1", label: "排产款，排期生产后" },
  { value: "2", label: "提货款，收到货物后" },
  { value: "3", label: "到货款，收到货物后" },
  { value: "4", label: "尾款，订单执行完成后" },
  { value: "9", label: "自定义" }
]);
// 付款节点时间列 - 选择框可选数据
const getAvailableNodeTriggerTypeList = (paymentCycle, nodeType) => {
  const availableOptions = nodeTriggerTypeOptions.filter(option => {
    switch (paymentCycle) {
      case "0": // 到货结算
        switch (nodeType) {
          case "0": // 合同预付款
            return ["0"].includes(option.value);
          case "1": // 订单预付款
            return ["1"].includes(option.value);
          default: // 订单实付款
            return ["1", "2", "3", "5", "6", "9"].includes(option.value);
        }
      case "1": // 款清发货
        switch (nodeType) {
          case "0": // 合同预付款
            return ["0"].includes(option.value);
          case "1": // 订单预付款
            return ["1"].includes(option.value);
          default: // 订单实付款
            return ["1", "4", "5", "6", "9"].includes(option.value);
        }
      case "2": // 月度结算
        switch (nodeType) {
          case "0": // 合同预付款
            return ["0"].includes(option.value);
          case "1": // 订单预付款
            return ["1"].includes(option.value);
          default: // 订单实付款
            return ["3", "9"].includes(option.value);
        }
      default:
        switch (nodeType) {
          case "0": // 合同预付款
            return ["0"].includes(option.value);
          case "1": // 订单预付款
            return ["1"].includes(option.value);
          default: // 订单实付款
            return ["9"].includes(option.value);
        }
    }
  });
  return availableOptions;
};
// 表格首行初始化(可能有潜在问题)
let nodePayTableData = ref([{ ...defaultPayNodeData }]);
let nodePayTableLoading = ref(false);
const nodePayTableColumns = reactive([
  {
    field: "nodeType",
    title: "节点类型",
    width: 150,
    align: "center",
    formatter({ cellValue, row }) {
      if (cellValue == "0") return "合同预付款";
      else if (cellValue == "1") return "订单预付款";
      else if (cellValue == "2") return "订单实付款";
      else return cellValue;
    }
  },
  {
    field: "payTime",
    title: "付款节点时间",
    width: 500
  },
  {
    field: "backPayRate",
    title: "完成付款比例（%）",
    width: 200
  },
  {
    field: "nodeMark",
    title: "节点说明",
    width: 400
  },
  {
    field: "operate",
    title: "操作",
    width: 80,
    fixed: "right",
    align: "center"
  }
]);
// 监听节点类型改变
watch(
  () => nodePayTableData.value.map(item => item.nodeType),
  (newNodeTypes, oldNodeTypes) => {
    const hasContractAdvance = newNodeTypes.includes("0");
    const hasOrderAdvance = newNodeTypes.includes("1");
    if (hasContractAdvance || hasOrderAdvance) {
      nodeTypeOptions[0].disabled = true;
      nodeTypeOptions[1].disabled = true;
    } else {
      nodeTypeOptions[0].disabled = false;
      nodeTypeOptions[1].disabled = false;
    }
  },
  { deep: true }
);
// 表单校验-stepTwo
const rulesForStepTwo = reactive({
  priceTypeMark: [
    { required: true, message: "请填写支付说明", trigger: "blur" }
  ],
  basePrice: [{ required: true, message: "请填写基准价", trigger: "blur" }],
  increasePrice: [{ required: true, message: "请填写涨幅", trigger: "blur" }],
  increaseRate: [{ required: true, message: "请填写涨幅比率", trigger: "blur" }]
});
// 添加付款节点
const addPaymentNode = () => {
  nodePayTableData.value.push({ ...defaultPayNodeData });
};
// 删除按钮，删除表格一行数据
const deletePayNodeData = row => {
  if (nodePayTableData.value.length === 1) {
    ElMessage.error("至少保留一行数据");
    return;
  }
  ElMessageBox.confirm("确认删除选中的行吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      if (row.id === "") {
        const index = nodePayTableData.value.findIndex(item => item === row);
        if (index > -1) {
          nodePayTableData.value.splice(index, 1);
        }
        ElMessage.success("删除成功");
      } else {
        const response: ApiResponse = await deletePayNode({
          id: row.id
        });
        if (response.code === 200) {
          ElMessage.success("删除成功");
          nodePayTableData.value = [];
          getStepTwoData();
        }
      }
    })
    .catch(() => {
      ElMessage.error("已取消");
    });
};
// 付款周期change事件
function changePaymentCycle() {
  if (nodePayTableData.value) {
    nodePayTableData.value.forEach(item => {
      item.nodeTriggerType = "";
      item.nodeTriggerTypeName = "";
    });
  }
}
// 表格数据 - 节点类型 change事件
function handleNodeTypeChange(row) {
  row.nodeTriggerType = "";
  row.nodeTriggerTypeName = "";
  if (row.nodeType) {
    row.nodeTypeName = nodeTypeOptions.find(
      item => item.value === row.nodeType
    ).label;
  }
}
// 表格数据 - 付款节点时间 change事件
function handleNodeTriggerTypeChange(row) {
  // 电线电缆业务
  if (contractModel.contractMethod === "0") {
    row.monthDay = 0;
    row.natureDay = 0;
    if (row.nodeTriggerType === "9") {
      row.autoStatus = "0";
      if (secondContractModel.paymentCycle === "2") {
        row.nodeTriggerTypeName = "项目部确认验收后";
      } else {
        row.nodeTriggerTypeName = "";
      }
    } else {
      row.autoStatus = "1";
      row.nodeTriggerTypeName = nodeTriggerTypeOptions.find(
        item => item.value === row.nodeTriggerType
      ).label;
    }
  }
  // 电梯扶梯业务
  else if (contractModel.contractMethod === "1") {
    if (row.nodeTriggerType === "9") {
      row.autoStatus = "0";
    } else {
      row.autoStatus = "1";
      row.nodeTriggerTypeName = nodeTriggerTypeForLift.find(
        item => item.value === row.nodeTriggerType
      ).label;
    }
  }
}
// 表格数据 - 节点说明 nodeMark赋值
function setNodeMarkForRow(row) {
  let nodeMark = "";
  if (secondContractModel.paymentCycle === "2") {
    if (row.nodeTriggerType === "9" && row.nodeType === "2") {
      nodeMark = `${row.nodeTriggerTypeName}，完成订单总金额 ${row.backPayRate}% 的回款`;
    } else if (row.nodeTriggerType !== "9" && row.nodeType === "2") {
      nodeMark = `${row.nodeTriggerTypeName} ${row.monthDay ?? 0} 个月 ${row.natureDay ?? 0} 日，完成订单总金额 ${row.backPayRate}% 的回款`;
    } else if (row.nodeType !== "2") {
      nodeMark = `${row.nodeTriggerTypeName} ${row.natureDay ?? 0} 个自然日，完成订单总金额 ${row.backPayRate}% 的回款`;
    }
  } else {
    if (row.nodeTriggerType === "9" && row.nodeType === "2") {
      nodeMark = `${row.nodeTriggerTypeName}，完成订单总金额 ${row.backPayRate}% 的回款`;
    } else if (row.nodeTriggerType !== "9" && row.nodeType === "2") {
      nodeMark = `${row.nodeTriggerTypeName} ${row.natureDay ?? 0} 个自然日，完成订单总金额 ${row.backPayRate}% 的回款`;
    } else if (row.nodeType !== "2") {
      nodeMark = `${row.nodeTriggerTypeName} ${row.natureDay ?? 0} 个自然日，完成订单总金额 ${row.backPayRate}% 的回款`;
    }
  }
  row.nodeMark = nodeMark;
}
// 获取第二步的数据详情
async function getStepTwoData() {
  nodePayTableLoading.value = true;
  let params: ApiParams = {};
  params.contractId = publicContractID.value;
  try {
    // 获取表单数据
    const formRes: ApiResponse = await getNodePayFormData(params);
    if (formRes.code === 200) {
      secondContractModel.id = formRes.data.id;
      secondContractModel.contractId = formRes.data.contractId;
      secondContractModel.priceType = formRes.data.priceType;
      secondContractModel.priceTypeMark = formRes.data.priceTypeMark;
      secondContractModel.basePrice = formRes.data.basePrice;
      secondContractModel.increasePrice = formRes.data.increasePrice;
      secondContractModel.increaseRate = formRes.data.increaseRate;
      secondContractModel.paymentCycle = formRes.data.paymentCycle;
      secondContractModel.paymentReconciliationMonth =
        formRes.data.paymentReconciliationMonth;
      secondContractModel.paymentReconciliationDay =
        formRes.data.paymentReconciliationDay;
      secondContractModel.contractPreStatus = formRes.data.contractPreStatus;
      secondContractModel.ordePreStatus = formRes.data.ordePreStatus;
    } else {
      ElMessage.error("获取合同付款方式表单失败");
    }
    // 获取表格数据
    const tableRes: any = await getNodePayTableData(params);
    if (tableRes.code == 200) {
      nodePayTableData.value = tableRes.data.records;
    } else {
      ElMessage.error("获取合同付款方式表格数据失败");
    }
  } catch (error) {
  } finally {
    nodePayTableLoading.value = false;
  }
}
// 保存第二步的数据请求
async function saveContractStepTwo() {
  /* 遍历表内容 nodePayTableData
   * 1.DOWN 存在 nodePayTableData[key].nodeType === '0' 的数据，secondContractModel.contractPreStatus = 1;
   * 2.DOWN 存在 nodePayTableData[key].nodeType === '1' 的数据，secondContractModel.ordePreStatus = 1;
   * 3.DOWN 存在 nodePayTableData[key].nodeTriggerType === '9'的数据，nodePayTableData[key].autoStatus = 0;
   * 4.DOWN nodePayTableData[key].nodeType != '0' 的数据中，backPayRate之和不为100，提示错误：“订单预付款及订单实付款节点比例和，需等于100”
   * 5.表格遍历时，将每一条数据 push进 secondContractModel.nodePaySaveDtoList 中
   * 6.DOWN secondContractModel,nodePayTableData[key]中部分数据，转换为number格式
   * 7.secondContractModel 参数整理
   * 8.DOWN 若非新增，需要传入ID，若新增，则不传
   * 9.DOWN 节点说明没有保存？
   * 10.DOWN 获取详情时，节点说明可能显示了两次
   * 11. nodeMark 赋值
   */
  let params: ApiParams = {};
  // 处理表单数据
  if (queryParams.action != "add") {
    params.id = secondContractModel.id;
  }
  params.contractId = publicContractID.value;
  params.priceType = secondContractModel.priceType;
  params.priceTypeMark = secondContractModel.priceTypeMark;
  if (secondContractModel.priceType === "1") {
    params.basePrice = Number(secondContractModel.basePrice);
    params.increasePrice = Number(secondContractModel.increasePrice);
    params.increaseRate = Number(secondContractModel.increaseRate);
  }
  params.paymentCycle = secondContractModel.paymentCycle;
  if (secondContractModel.paymentCycle == "2") {
    // 电线电缆
    if (contractModel.contractMethod === "0") {
      params.paymentReconciliationMonth = Number(
        nodePayTableData.value.find(
          row => row.nodeType === "2" && row.nodeTriggerType === "3"
        ).monthDay
      );
      params.paymentReconciliationDay = Number(
        nodePayTableData.value.find(
          row => row.nodeType === "2" && row.nodeTriggerType === "3"
        ).natureDay
      );
    }
    // 电梯扶梯
    else if (contractModel.contractMethod === "1") {
      params.paymentReconciliationMonth = Number(
        nodePayTableData.value.find(row => row.nodeType === "2").monthDay
      );
      params.paymentReconciliationDay = Number(
        nodePayTableData.value.find(row => row.nodeType === "2").natureDay
      );
    }
  }
  if (nodePayTableData.value.find(row => row.nodeType === "0")) {
    params.contractPreStatus = 1;
  }
  if (nodePayTableData.value.find(row => row.nodeType === "1")) {
    params.orderPreStatus = 1;
  }
  // 处理表格数据
  nodePayTableData.value.forEach(row => {
    setNodeMarkForRow(row);
  });
  let tempList = [];
  for (let i = 0; i < nodePayTableData.value.length; i++) {
    nodePayTableData.value[i].contractId = publicContractID.value;
    tempList.push({ ...nodePayTableData.value[i] });
  }
  params.nodePaySaveDtoList = tempList;
  await saveNodePayData(params);
}
////////////////////// 第三步 //////////////////////
// stepThree表格数据
let materialTableData = ref([]);
let materialTableFooterData = ref<VxeTablePropTypes.FooterData>([
  {
    seq: "合计",
    materialNum: computed(() => {
      return parseFloat(
        materialTableData.value
          .reduce((total, row) => {
            return total + (Number(row.materialNum) || 0);
          }, 0)
          .toFixed(4)
      );
    }),
    includingTaxTotalPrice: computed(() => {
      return parseFloat(
        materialTableData.value
          .reduce((total, row) => {
            return total + (Number(row.includingTaxTotalPrice) || 0);
          }, 0)
          .toFixed(4)
      );
    })
  }
]);
let materialTableLoding = ref(false);
let materialTableRef = ref(null);
const materialTableColumns = reactive([
  {
    field: "materialCode",
    title: "材料编码",
    width: 120,
    align: "center"
  },
  {
    field: "materialName",
    title: "材料名称",
    width: 120,
    align: "center"
  },
  {
    field: "materialSpecs",
    title: "规格",
    width: 180,
    align: "center"
  },
  {
    field: "materialModel",
    title: "型号",
    width: 120,
    align: "center"
  },
  {
    field: "materialUnit",
    title: "单位",
    width: 120,
    align: "center"
  },
  {
    field: "materialBrand",
    title: "品牌",
    width: 120,
    align: "center"
  },
  {
    field: "materialNum",
    title: "数量",
    width: 120,
    fixed: "right",
    align: "right"
  },
  {
    field: "includingTaxUnitPrice",
    title: "含税单价（元）",
    width: 120,
    fixed: "right",
    align: "right"
  },
  {
    field: "excludingTaxUnitPrice",
    title: "不含税单价（元）",
    width: 150,
    fixed: "right",
    align: "right"
  },
  {
    field: "tax",
    title: "税率（%）",
    width: 120,
    fixed: "right",
    align: "right"
  },
  {
    field: "includingTaxTotalPrice",
    title: "含税总价（元）",
    width: 150,
    fixed: "right",
    align: "right"
  },
  {
    field: "materialMark",
    title: "备注",
    width: 120,
    fixed: "right",
    align: "center"
  }
]);
const materialTablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 999
});
// const materialTablePageChange: VxePagerEvents.PageChange = ({
//   currentPage,
//   pageSize
// }) => {
//   materialTablePage.currentPage = currentPage;
//   materialTablePage.pageSize = pageSize;
//   getStepThreeData();
// };
// 选择材料弹窗
let materialSelectDialogVisible = ref(false);
function showMaterialSelectDialog() {
  materialSelectDialogVisible.value = true;
}
function closeMaterialSelectDialog(val: boolean) {
  materialSelectDialogVisible.value = val;
}
const materialSelectConfirm = data => {
  materialTableData.value.push({
    ...data.selectedRow,
    materialSpecs: data.selectedRow.materialSpecifications,
    contractId: publicContractID.value,
    materialId: data.selectedRow.id,
    id: ""
  });
};
// 下载模板
function downloadTemplate() {
  const url = "/doc/materialTemplate.xlsx";
  fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = "销售合同材料清单模板.xlsx";
      link.click();
      URL.revokeObjectURL(link.href);
    })
    .catch(error => {});
}
// 导入模板
const fileInputRef = ref<HTMLInputElement | null>(null);
function triggerFileSelect() {
  if (fileInputRef.value) {
    (fileInputRef.value as HTMLInputElement).click();
  }
}
function handleFileChange(event: Event) {
  const inputElement = event.target as HTMLInputElement;
  const file = inputElement.files?.[0];
  if (file) {
    importMaterialData(file).catch(error => {
      ElMessage.error("文件导入失败:" + error);
    });
  }
}
async function importMaterialData(file: File): Promise<void> {
  const formData = new FormData();
  formData.append("file", file);
  if (publicContractID.value) {
    formData.append("contractId", publicContractID.value.toString());
  }
  try {
    const response: ApiResponse = await importMaterialList(formData);
    if (response.code === 200) {
      ElMessage.success("材料导入成功!");
      getStepThreeData();
    } else {
      ElMessage.error(response.msg || "导入失败，未知错误");
    }
  } catch (error) {
    ElMessage.error("文件导入失败: " + error.message || "未知错误");
  }
}
// 值计算属性
function changeCalculated(row, type) {
  switch (type) {
    case "materialNum":
      if (row.includingTaxUnitPrice) {
        row.includingTaxTotalPrice = parseFloat(
          (row.materialNum * row.includingTaxUnitPrice).toFixed(4)
        );
      }
      break;
    case "includingTaxUnitPrice":
      if (row.materialNum) {
        row.includingTaxTotalPrice = parseFloat(
          (row.materialNum * row.includingTaxUnitPrice).toFixed(4)
        );
      }
      if (row.materialNum && row.tax) {
        row.excludingTaxUnitPrice = parseFloat(
          (row.includingTaxUnitPrice / (1 + row.tax / 100)).toFixed(4)
        );
      }
      break;
    case "excludingTaxUnitPrice":
      if (!row.materialNum) return;
      row.includingTaxTotalPrice = parseFloat(
        (row.materialNum * row.includingTaxUnitPrice).toFixed(4)
      );
      row.includingTaxUnitPrice = parseFloat(
        (row.excludingTaxUnitPrice * (1 + row.tax / 100)).toFixed(4)
      );
      break;
    case "tax":
      row.excludingTaxUnitPrice = parseFloat(
        (row.includingTaxUnitPrice / (1 + row.tax / 100)).toFixed(4)
      );
      row.includingTaxTotalPrice = parseFloat(
        (row.materialNum * row.includingTaxUnitPrice).toFixed(4)
      );
      break;
    case "includingTaxTotalPrice":
      if (!row.materialNum || !row.tax) return;
      row.includingTaxUnitPrice = parseFloat(
        (row.includingTaxTotalPrice / row.materialNum).toFixed(4)
      );
      row.excludingTaxUnitPrice = parseFloat(
        (row.includingTaxUnitPrice / (1 + row.tax / 100)).toFixed(4)
      );
      break;
  }
}
// 点击行复制按钮事件
const copyRow = row => {
  const { _X_ROW_KEY, ...newRow } = JSON.parse(JSON.stringify(row));
  newRow.id = "";
  const currentIndex = materialTableData.value.indexOf(row);
  if (currentIndex === -1) return;
  materialTableData.value.splice(currentIndex + 1, 0, newRow);
};
// 导出文件
async function exportMaterialList() {
  let params: ApiParams = {};
  params.contractId = publicContractID.value;
  params.contractNo = contractModel.contractNo;
  saveContractStepThree().then(async () => {
    const response: ApiResponse = await exportMaterialListFile(params);
    if (response.code === 200) {
      const url = response.data;
      window.open(url);
    } else {
      ElMessage.error(response.msg || "导出失败，未知错误");
    }
  });
}
// 删除单条材料
async function singleDeleteMeterial(row) {
  ElMessageBox.confirm("确定删除该条数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      let params = {
        contractId: publicContractID.value,
        idList: []
      };
      params.idList.push(row.id);
      try {
        if (row.id === "") {
          const index = materialTableData.value.findIndex(item => item === row);
          if (index > -1) {
            materialTableData.value.splice(index, 1);
          }
          ElMessage.success("删除成功");
        } else {
          const response: ApiResponse = await deleteContractMaterial(params);
          if (response.code === 200) {
            ElMessage.success("删除成功");
            getStepThreeData();
          }
        }
      } catch (error) {}
    })
    .catch(() => {
      ElMessage.error("已取消");
    });
}
// 获取选中行
function getSelectedRows() {
  return materialTableRef.value.getCheckboxRecords().map(row => ({
    id: row.id
  }));
}
// 删除多条材料
async function complexDeleteMaterials() {
  const selectedMaterialRows = getSelectedRows();
  if (selectedMaterialRows.length === 0) {
    ElMessage.warning("请至少选择一行进行删除！");
    return;
  }
  ElMessageBox.confirm("确定删除选中的条数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const indicesToRemove = [];
        const idList = [];
        selectedMaterialRows.forEach(row => {
          if (row.id === "") {
            // 仅在表中删除 row
            const index = materialTableData.value.findIndex(
              item => item.id === row.id
            );
            if (index > -1) {
              indicesToRemove.push(index);
            }
          } else {
            // 通过请求删除 idList
            idList.push(row.id);
          }
        });
        if (idList.length > 0) {
          const params = {
            contractId: publicContractID.value,
            idList: idList
          };
          const response: ApiResponse = await deleteContractMaterial(params);
          if (response.code === 200) {
            ElMessage.success("批量删除成功！");
            getStepThreeData();
          }
          // else {
          //   ElMessage.error("批量删除失败：" + response.msg || "未知错误");
          // }
        }
        // 根据索引从大到小进行删除，防止索引错乱
        indicesToRemove
          .sort((a, b) => b - a)
          .forEach(idx => {
            materialTableData.value.splice(idx, 1);
          });
      } catch (error) {}
    })
    .catch(() => {
      ElMessage.info("已取消删除操作。");
    });
}
// 保存第三步的数据请求
async function saveContractStepThree(type?: any) {
  let params: ApiParams = {
    contractId: publicContractID.value,
    saveDtoList: []
  };
  for (let items in materialTableData.value) {
    params.saveDtoList.push({ ...materialTableData.value[items] });
  }
  const stepThreeRes: any = await saveContractMeterialData(params);
  if (stepThreeRes.code === 200) {
    if (type == "submit") {
      let params: ApiParams = {};
      params.id = publicContractID.value;
      submitAudit(params).then((response: ApiResponse) => {
        if (response.code === 200) {
          ElMessage.success("提交成功");
        } else {
          ElMessage.error("提交失败");
          ElMessage.error("失败原因：" + response.msg);
        }
      });
    }
    // 统计数据由前端执行计算了 edit by YUM 241008
    // await getContractMaterialFooter({ contractId: publicContractID.value });
  }
}
// 获取第三步的数据详情
async function getStepThreeData() {
  materialTableLoding.value = true;
  let params: ApiParams = {};
  params.pageIndex = materialTablePage.currentPage;
  params.pageSize = materialTablePage.pageSize;
  params.contractId = publicContractID.value;
  try {
    const tableRes: any = await getContractMaterialList(params);
    // 统计数据由前端执行计算了 edit by YUM 241008
    // const footRes: any = await getContractMaterialFooter(params);
    if (tableRes.code == 200) {
      materialTableData.value = tableRes.data.records;
      materialTablePage.total = tableRes.data.totalElements;
    } else {
      ElMessage.error("获取合同材料表格数据失败");
    }
    // if (footRes.code === 200) {
    //   materialTableFooterData.value = [];
    //   materialTableFooterData.value.push({
    //     materialNum: footRes.data.totalNum,
    //     includingTaxTotalPrice: footRes.data.totalPrice
    //   });
    // } else {
    //   ElMessage.error("获取合同材料表格页脚数据失败");
    // }
  } catch (error) {
  } finally {
    materialTableLoding.value = false;
  }
}
////////////////////// 公共 //////////////////////
// 保存并下一步按钮事件
async function nextStep() {
  if (active.value == 0) {
    // 第一页保存
    try {
      const formsRefs = [contractModelRef1, contractModelRef2];
      await proceedIfAllValid(formsRefs);
      // 若非新增，则获取第二页数据
      if (queryParams.action != "add") {
        await getStepTwoData();
      }
    } catch (error) {
      ElMessage.error("请检查合同信息是否正确！");
    }
  } else if (active.value == 1) {
    // 第二页保存
    try {
      const formsRefs = [secondContractModelRef];
      await proceedIfAllValid(formsRefs);
    } catch (error) {
      ElMessage.error("请检查付款节点表单是否填写正确！");
      console.log(error);
    }
    // 若非新增，则获取第三页数据
    if (queryParams.action != "add") {
      await getStepThreeData();
    }
  } else {
    // 第三页保存
    try {
      await saveContractStepThree();
      // 关闭标签页，成功提示
      //TODO 可能需要放入第三步的请求中处理关闭页面
      document.getElementById("closeTagButtonRef").click();
      ElMessage({
        showClose: true,
        message: "保存成功！",
        type: "success"
      });
    } catch (error) {
      ElMessage.error("请检查合同材料是否正确！");
    }
  }
}
// 表单校验通过，保存
async function proceedIfAllValid(formsRefs) {
  const allValid = await validateFormSequentially(formsRefs);
  if (allValid) {
    switch (active.value) {
      case 0:
        await saveContractStepOne();
        break;
      case 1:
        await saveContractStepTwo();
        break;
      case 2: // case 2 这里其实用不到
        await saveContractStepThree();
        break;
      default:
        ElMessage.error("未匹配到active.value！");
        break;
    }
    active.value += 1;
  }
}
// 多el-card表单验证
async function validateFormSequentially(formsRefs) {
  for (const formRef of formsRefs) {
    // 第一步表单验证
    if (active.value === 0) {
      try {
        const valid = await formRef.value.validate();
        if (!valid) {
          return false;
        }
      } catch (error) {
        ElMessage.error("输入有误，请检查！");
        return false;
      }
    }
    // 第二步表单验证
    else if (active.value === 1) {
      try {
        const valid = await formRef.value.validate();
        if (!valid) {
          return false;
        }
        // 比率之和计算
        let num = 0;
        for (let item in nodePayTableData.value) {
          num += Number(nodePayTableData.value[item].backPayRate);
        }
        if (num != 100) {
          ElMessage.error("付款比例之和需等于100！当前：" + num);
          return false;
        }
      } catch (error) {
        ElMessage.error("输入有误，请检查！");
        return false;
      }
    }
    // 第三步表单验证
    else if (active.value === 2) {
      if (materialTableData.value.length === 0) {
        ElMessage.error("请添加合同材料！");
        return false;
      }
    }
  }
  return true;
}
// 保存并提交
async function saveOrSubmit() {
  try {
    await saveContractStepThree("submit");
    document.getElementById("closeTagButtonRef").click();
  } catch (error) {
    ElMessage.error("请检查合同材料是否正确！");
  }
}
// 初始化
onMounted(() => {
  // TODO - 应该根据 当前展示的页面 && 是否为非新增 来判断是否需要初始化数据
  // 路由传参 - 获取合同类型
  if (queryParams && queryParams.contractType !== undefined) {
    if (queryParams.contractType === "0" || queryParams.contractType === "1") {
      contractModel.contractType = queryParams.contractType;
    }
  }
  // 获取合同详情 - 第一页 - 供应商品类列表字典
  getSupplierCategoryNameOptions();
  // 获取合同详情 - 第一页 - 供应列表字典
  getSupplyDeptOptions();
  // 非新增时触发获取第一页详情
  if (active.value === 0 && queryParams.action != "add") {
    // 获取合同详情 - 第一页
    getStepOneData();
    // 获取合同ID
    contractModel.id = queryParams.id.toString();
    // 获取项目收货人表格
    getProjectReceiverList();
    // 联系人对照表赋值 - 用来看收获人表格是否改动，目前可能有bug
    contractTableOrigData.value = cloneDeep(contactsTableData.value);
  }
});
</script>

<style lang="scss" scoped>
.step3Head {
  .step3HeadBtn {
    display: inline-block;
    margin-left: 1%;
  }
  .step3HeadText {
    display: inline-block;
    width: 600px;
    margin-left: 1%;
    .step3HeadTips {
      display: inline-block;
      font-size: 12px;
      .tipsTitle {
        display: inline-block;
        width: 80px;
        height: 20px;
        border: 1px solid #b8bac2;
        border-radius: 10px;
        text-align: center;
      }
      .tipsContent {
        display: inline;
        margin-left: 5%;
      }
    }
  }
  .step3EndBtn {
    float: right;
  }
}
</style>
